package com.xuliugen.demo.multithread.treadlocal;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * Created by xuliugen on 2017/11/13.
 */
public class WeakRefrenceDemo {

    /**
     * 引用队列
     */
    private static ReferenceQueue<User> referenceQueue = new ReferenceQueue<>();

    public static void main(String[] args) {

        User user = new User("hello", "123");
        WeakReference<User> userWeakReference = new WeakReference<>(user, referenceQueue);
        System.out.println(userWeakReference.get());
        user = null; //断开引用
        System.gc(); //强制执行GC
        System.runFinalization();
        System.out.println(userWeakReference.get());
    }

    public static class User {
        private String userName;
        private String userPwd;

        User(String userName, String userPwd) {
            this.userName = userName;
            this.userPwd = userPwd;
        }

        @Override
        public String toString() {
            return "User{" +
                    "userName='" + userName + '\'' +
                    ", userPwd='" + userPwd + '\'' +
                    '}';
        }
    }
}
